//
//  SearchResultStoreViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/22.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "HZLocation.h"

#import "StoreCategoryListCell.h"
#import "StoreDetailViewController.h"

#import "StoreHotelDetailViewController.h"
#import "SearchResultStoreViewController.h"

@interface SearchResultStoreViewController ()<UITableViewDelegate, UITableViewDataSource, HZLocationDelegate>

@property (nonatomic, strong) HZLocation *locationManager;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <CommonSellerModule *>*dataArray;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation SearchResultStoreViewController

- (instancetype)initWithKeyWord:(NSString *)keyWord {
    
    self = [super init];
    
    if (self) {
        self.keyWord = keyWord;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    
    self.locationManager ;

    [self refreshParam];
    [self request_searchStore];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchCallBack:) name:@"searchNoti" object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)searchCallBack:(NSNotification *)Noti {
    
    self.keyWord = [Noti.userInfo objectForKey:@"keyWord"];
    [self refreshParam];
    [self request_searchStore];
}

- (void)refreshParam {
    
    self.pageNum = 1;
    self.pageSize = 10;
}

- (void)initView {
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    [self initViewAction];
}

- (void)initViewAction {

}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return  [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [StoreCategoryListCell calculateHeightWithModel:self.dataArray[indexPath.row]];;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.dataArray[indexPath.row].classId isEqualToString:Store_Category_Hotel]) {
        StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].sellerId;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].sellerId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StoreCategoryListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreCategoryListCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
//    WEAKSELF
    cell.StoreCategoryListCellBlock = ^{
    };
    
    return cell;
}

- (NSMutableArray<CommonSellerModule *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"StoreCategoryListCell" bundle:nil] forCellReuseIdentifier:@"StoreCategoryListCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_searchStore];
        }];
//
        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum++;
            [weakSelf request_searchStore];
        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}

- (HZLocation *)locationManager {
    
    if (!_locationManager) {
        _locationManager = [[HZLocation alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}

//定位成功
- (void)currentLocation:(NSDictionary *)locationDictionary coordinate:(CLLocationCoordinate2D)coordinate {

    [[TTUserModel sharedObject].userModelDefault setDouble:coordinate.latitude forKey:@"TT_latitude"];
    [[TTUserModel sharedObject].userModelDefault setDouble:coordinate.longitude forKey:@"TT_longitude"];
    
    if (self.dataArray.count > 0) {
        
        for (CommonSellerModule *model in self.dataArray) {
            
            if (model.lat > 0 && model.lng > 0) {
                model.distance = [Utilities calculateStart:CLLocationCoordinate2DMake([TTUserModel sharedObject].latitude, [TTUserModel sharedObject].longitude) end:CLLocationCoordinate2DMake(model.lat,model.lng)];
            }
        }
        [self.tableview reloadData];
    }
}

/// 拒绝定位
- (void)refuseToUsePositioningSystem:(NSString *)message {
    NSLog(@"%@",message);

}

/// 定位失败
- (void)locateFailure:(NSString *)message {
    NSLog(@"%@",message);


}

- (void)request_searchStore {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSDictionary *t = @{}.mutableCopy;
    [t setValue:self.keyWord forKey:@"searchName"];
    [t setValue:[TTUserModel sharedObject].cityId forKey:@"sellerCityId"];
    [t setValue:@"1" forKey:@"type"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SearchAll];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if (weakSelf.pageNum == 1) {
                        weakSelf.dataArray = @[].mutableCopy;
     
                        if (list.count == 0) {
                            
                            [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_NoSearchResult btnTitle:@"去问统筹师" didPressButton:^{
                                
//                                你好，关于“搜索词”商家/套餐/案例/婚品，没有搜索到结果，我这边想咨询下
                                NSString *imStr = [NSString stringWithFormat:@"你好，关于“%@”商家，没有搜索到结果，我这边想咨询下",self.keyWord];
                                [[TT_IMContactManager manager] ImContactWithType:TT_IMContactType_tongchoushi withQuickReply:imStr];
                                
                            }];
                            
                        }
                    }
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        for (int i = 0; i < list.count; i++) {
                            NSDictionary *listDic = list[i];
                            CommonSellerModule *model = [CommonSellerModule modelWithDictionary:listDic];
                            
                            NSDictionary *sellerQualityAuthentication = [listDic valueForKey:@"sellerQualityAuthentication"];
                            model.sellerQualityAuthentication = [CommonQualityTagModel modelWithDictionary:sellerQualityAuthentication];
                            
                            if (model.lat > 0 && model.lng > 0) {
                                model.distance = [Utilities calculateStart:CLLocationCoordinate2DMake([TTUserModel sharedObject].latitude, [TTUserModel sharedObject].longitude) end:CLLocationCoordinate2DMake(model.lat,model.lng)];
                            }
                            
                            NSArray *coverPaths = [listDic valueForKey:@"coverPaths"];
                            
                            if ([coverPaths isKindOfClass:[NSArray class]]) {
                                model.coverPaths = @[].mutableCopy;
                                for (int j = 0; j < coverPaths.count; j++) {
                                    NSDictionary *coverPathsDic = coverPaths[j];
                                    CommonImageModel *imgModel = [CommonImageModel modelWithDictionary:coverPathsDic];
                                    [model.coverPaths addObject:imgModel];
                                }
                            }
                            
                            [weakSelf.dataArray addObject:model];
                        }
                    }

                    [weakSelf.tableview reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}


@end
